namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using SimpleWebServices.Web;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    public sealed class CacheControlAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (null == filterContext)
            {
                throw new ArgumentNullException("filterContext");
            }

            base.OnActionExecuted(filterContext);

            HttpResponseBase response = filterContext.HttpContext.Response;

            IResource resource = filterContext.Controller.ViewData.Model as IResource;
            if (null != resource)
            {
                response.Cache.SetCacheability(resource.Cacheability.HasValue ? resource.Cacheability.Value : HttpCacheability.Public);
                
                if (null != resource.Etag)
                {
                    response.Cache.SetETag(resource.Etag);
                }

                if (null != resource.Expires)
                {
                    DateTime expires = resource.Expires;
                    response.Cache.SetExpires(expires);
                    if (expires > DateTime.UtcNow)
                    {
                        response.Cache.SetMaxAge(expires - DateTime.UtcNow);
                    }
                }

                if (resource.Modified.HasValue)
                {
                    response.Cache.SetLastModified(resource.Modified.Value);
                }
            }
        }
    }
}